package com.exceeddata.vcloud.common.exception;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import com.exceeddata.vcloud.common.response.ResultUtil;
import com.exceeddata.vcloud.common.tools.StringTool;

import java.util.Map;

/**
 * 描述: 全局异常处理
 * 创建人: 赵兴炎
 * 日期: 2022年9月5日
 */
@ControllerAdvice
public class ServiceExceptionHandler {

	private final Logger logger = LoggerFactory.getLogger(ServiceExceptionHandler.class);

	/**
	 * 描述: 处理自定义异常
	 * 创建人: 赵兴炎
	 * 日期: 2022年9月5日
	 */
	@ExceptionHandler(value = ServiceRunTimeException.class)
	public ResponseEntity<Object> ServiceRunTimeExceptionHandler(HttpServletResponse response, ServiceRunTimeException serviceRunTimeException) {
		// 获取异常信息
		String message = serviceRunTimeException.getMessage();
		// 获取异常信息详情
		String describe = serviceRunTimeException.getDescribe();
		// 控制台输出异常信息
		logger.error(message+"--------------"+describe);
		HttpStatus httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
		Map<String, Object> errorResult = ResultUtil.error(httpStatus.value(), message, describe);
		return ResponseEntity.status(httpStatus.value()).body(errorResult);
	}

	/**
	 * 描述: 处理自定义异常以外的异常
	 * 创建人: 赵兴炎
	 * 日期: 2022年9月5日
	 */
	@ExceptionHandler(value = Exception.class)
	public ResponseEntity<Object> defaultErrorHandler(HttpServletResponse response, Exception exception) {
		exception.printStackTrace();
//		logger.error("未知异常", exception);
		// 获取异常信息
		String message = exception.getMessage();
		HttpStatus httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
		Map<String, Object> errorResult = ResultUtil.error(httpStatus.value(), message, StringTool.exceptionToString(exception));
		return ResponseEntity.status(httpStatus.value()).body(errorResult);
	}

}
